﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text;

public class RC4
{
    private const int N = 256;
    private int[] sbox;
    private string password;

    public RC4(string password)
    {
        this.password = password;
    }


    public string Password
    {
        get { return password; }
        set { password = value; }
    }

    public string EnDeCrypt(string text)
    {
        RC4Initialize();

        int i = 0, j = 0, k = 0;
        StringBuilder cipher = new StringBuilder();
        for (int a = 0; a < text.Length; a++)
        {
            i = (i + 1) % N;
            j = (j + sbox[i]) % N;
            int tempSwap = sbox[i];
            sbox[i] = sbox[j];
            sbox[j] = tempSwap;

            k = sbox[(sbox[i] + sbox[j]) % N];
            int cipherBy = ((int)text[a]) ^ k;  //xor operation
            cipher.Append(Convert.ToChar(cipherBy));
        }
        return cipher.ToString();
    }
       

    private void RC4Initialize()
    {
        sbox = new int[N];
        int[] key = new int[N];
        int n = password.Length;
        for (int a = 0; a < N; a++)
        {
            key[a] = (int)password[a % n];
            sbox[a] = a;
        }

        int b = 0;
        for (int a = 0; a < N; a++)
        {
            b = (b + sbox[a] + key[a]) % N;
            int tempSwap = sbox[a];
            sbox[a] = sbox[b];
            sbox[b] = tempSwap;
        }
    }


}

